<template>
  <div class="order_purchase">
    <div class="purchase_head">
      <div class="head_left">
        <div class="round" />
        <div>
          发起测量预购单
          <span style="font-size: 12px; color: #86909c">
            （测量单不属于采购单，如：“门”需要测量后在在下单的可以发起测量等供应商上门测量确认价格后再采购！）
          </span>
        </div>
      </div>
      <div class="head_right">
        <el-button class="right_btn" @click="goBack()">返回</el-button>
      </div>
    </div>
    <div class="purchase_content">
      <div class="content_table">
        <div class="content_title">供应商信息</div>
        <div class="info_box mt12">
          <div>
            <div class="info_label">企业名称:</div>
            <div>{{ factoryInfo.anotherName }}</div>
          </div>
          <div>
            <div class="info_label">跟单人员:</div>
            <div>{{ factoryInfo.trackerName }}</div>
          </div>
          <div>
            <div class="info_label">工厂地址:</div>
            <div>{{ factoryInfo.factorAddress }}</div>
          </div>
          <div>
            <div class="info_label">跟单人电话:</div>
            <div>{{ factoryInfo.trackerTel }}</div>
          </div>
          <div>
            <div class="info_label">是否支持开票:</div>
            <div v-if="factoryInfo.isSupportBilling">
              {{ `支持开票(专票${factoryInfo.specialTicket}%)(普票${factoryInfo.ordinaryTicket}%)` }}
            </div>
            <div v-else>不支持开票</div>
          </div>
        </div>
        <div class="content_title mt12">商品信息</div>
        <el-table
          border
          class="mt12"
          :data="factoryInfo.list"
          style="width: 100%"
          header-cell-class-name="table_head"
          @selection-change="handleSelectionChange"
        >
          <el-table-column v-if="!updateId" label="商品信息" type="selection" width="40" />
          <el-table-column label="商品信息" min-width="330">
            <template #default="{ row }">
              <div class="goods_cell">
                <img class="cell_image" :src="row.mainPicUrl" />
                <div class="cell_product">
                  <div class="product_name">{{ row.productAliasName }}</div>
                  <div class="product_info">{{ row.skuSpecification }}</div>
                  <div class="product_info">SKU编码:{{ row.skuCode }}</div>
                  <div class="product_info">ID：{{ row.productId }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center" min-width="200">
            <template #default="{ row }">
              <RemarkEditor v-model="row.remark" :isEdit="true" />
            </template>
          </el-table-column>
          <el-table-column prop="supplyUnitPrice" label="供应单价" align="center" width="100">
            <template #default="{ row }"> ¥{{ row.supplyUnitPrice }} </template>
          </el-table-column>
          <el-table-column prop="buyNum" label="数量" max-width="100" />
          <el-table-column prop="buyPartNum" label="商品件数" width="100" />
          <el-table-column prop="measureDataRemark" label="测量数据反馈" width="200" show-overflow-tooltip>
            <template #default="{ row }">
              {{ row.measureDataRemark || "-" }}
            </template>
          </el-table-column>
          <el-table-column prop="measurePrice" label="测量定价" width="130" />
        </el-table>
      </div>
      <div class="content_form">
        <div class="form_content">
          <el-form ref="formRef" :model="detailInfo" :rules="rules" label-width="auto" status-icon>
            <el-form-item label="测量时间" prop="expectedMeasureTime">
              <el-date-picker
                v-model="detailInfo.expectedMeasureTime"
                type="datetime"
                placeholder="请选择"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="是否开票" prop="" required>
              <div style="display: flex; justify-content: space-between; width: 100%; background: #f5f7fa; padding: 0 20px">
                <el-radio-group v-model="detailInfo.isBusinessInvoice" @change="isBusinessInvoiceChange">
                  <div class="business-invoice">
                    <div class="is-business-invoice">
                      <el-radio :value="1">开票</el-radio>
                      <el-radio-group
                        class="radio-button"
                        v-model="detailInfo.invoiceType"
                        v-if="detailInfo.isBusinessInvoice === 1"
                        size="small"
                        @change="invoiceTypeChange"
                      >
                        <el-radio-button label="专票" :value="1" />
                        <el-radio-button label="普票" :value="2" />
                      </el-radio-group>
                    </div>
                    <el-radio :value="0">不开票</el-radio>
                  </div>
                </el-radio-group>
                <div
                  v-if="factoryInfo.isSupportBilling == 0 && detailInfo.isBusinessInvoice === 1"
                  style="color: #ff3333; font-size: 12px"
                >
                  当前供应商不支持开票，请致电沟通后在提交采购单！
                </div>
              </div>
              <!-- <div class="warehouse_content" v-if="detailInfo.isBusinessInvoice === 1">
                <el-select v-model="detailInfo.invoiceType" placeholder="请选择开票类型" @change="invoiceTypeChange">
                  <el-option label="专票" :value="1" />
                  <el-option label="普票" :value="2" />
                </el-select>
              </div> -->
            </el-form-item>
            <el-form-item label="测量单备注">
              <RemarkEditor v-model="detailInfo.remark" />
            </el-form-item>
          </el-form>
        </div>
        <div class="form_info">
          <div class="info_box" style="display: block">
            <div class="info_title mb10">测量地址</div>
            <div class="info_label mt10">姓名:</div>
            <div>{{ detailInfo.receivingName }}</div>
            <div class="info_label mt10">电话:</div>
            <div>{{ detailInfo.receivingMobile }}</div>
            <div class="info_label mt10">
              收货地址:
              <el-button
                v-if="detailInfo.isClose !== 1 && detailInfo.orderStatus !== 3"
                class="ml10"
                type="primary"
                link
                @click="openUpdateReceiptInfoModal"
              >
                修改
                <img class="ml10" style="width: 16px; height: 16px" src="@/assets/images/edit.png" />
              </el-button>
            </div>
            <div v-if="detailInfo.receivingAreaIds">{{ detailInfo.receivingAreaDetail }}{{ detailInfo.receivingAddress }}</div>
            <div v-else>{{ detailInfo.receivingAddress }}</div>
            <div class="info_title mb10 mt20">买家信息</div>
            <div class="info_label mt10">姓名:</div>
            <div>{{ detailInfo.customerName }}</div>
            <div class="info_label mt10">电话:</div>
            <div>{{ detailInfo.customerMobileCode }}</div>
            <div class="info_label mt10">项目地址:</div>
            <div>{{ detailInfo.customerAddress }}</div>
          </div>
        </div>
      </div>
      <el-affix position="bottom" :offset="20" style="width: 100%">
        <div class="affix_content">
          <div class="content_left">
            <div class="left_tip" v-if="detailInfo.isBusinessInvoice === 1">
              <span class="info_lable">税额：</span>
              <span class="mr20">¥{{ detailInfo.feeAmount || 0 }}</span>
            </div>
            <span item>测量单总金额：</span>
            <span class="mr20">¥{{ calcActualTotal(selectedList) }}</span>
          </div>
          <div class="content_right">
            <el-button class="btn right_btn" @click="goBack()">取消</el-button>
            <el-button class="btn" type="primary" @click="handelClickCreateProcure(detailInfo)">发起测量单</el-button>
          </div>
        </div>
      </el-affix>
    </div>
    <UpdateReceiptInfoDialog
      v-if="updateReceiptInfoFlag"
      v-model="updateReceiptInfoFlag"
      :orderDetail="detailInfoCache"
      @success="successHandle"
      :isPostApi="false"
    />

    <dialog-View :isShow="purchaseSuccessFlag" :width="600">
      <div class="procure_success">
        <div><img src="@/static/images/suceess.png" /></div>
        <div style="text-align: center; line-height: 22px">
          测量单已提交成功，等待供应商接单上门测量数据并回传定价数据， 是否前往测量单管理查看详情？ ~
        </div>
        <div>
          <el-button @click="purchaseSuccessFlag = false">关闭</el-button>
          <el-button type="primary" @click="routeToPurchaseOrder">前往查看</el-button>
        </div>
      </div>
    </dialog-View>
  </div>
</template>
<script setup>
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { createMeasureOrder, getOrderDetail, getPayAccountList } from "@/apis/order";
import RemarkEditor from "@/components/RemarkEditor";
import UpdateReceiptInfoDialog from "../productOrders/components/updateReceiptInfoDialog.vue";
import { ElMessage } from "element-plus";
import { getlistByTenantId } from "@/apis/procure";
import dialogView from "../components/dialogView.vue";

const route = useRoute();
const router = useRouter();
const orderId = route.query.orderId;
const factorId = route.query.factorId;

const formRef = ref();
const detailInfo = ref({});
const detailInfoCache = ref({});
const factoryInfo = ref({});
const warehouseList = ref([]);
const payAccountList = ref([]);

const selectedList = ref([]);

const updateReceiptInfoFlag = ref(false);
const purchaseSuccessFlag = ref(false);

const goBack = () => router.go(-1);

const routeToPurchaseOrder = () => router.push("/oder/measure");

const calcTotal = ({ buyNum, supplyUnitPrice }, discountRate) => {
  const total = Number(buyNum) * Number(supplyUnitPrice) * (Number(discountRate || 100) / 100);
  return total.toFixed(2);
};

const calcActualTotal = list => {
  return list.reduce((sum, cur) => sum + Number(cur.actualAmount), 0);
};

// 算总金额
const calcTotalPrice = () => {
  detailInfo.value.totalPrice = calcActualTotal(factoryInfo.value.list);

  const actualAmountTotal = calcActualTotal(selectedList.value);

  detailInfo.value.commodityPrice = actualAmountTotal + Number(detailInfo.value.otherFee) - detailInfo.value.discountAmount;

  detailInfo.value.discountTotal = selectedList.value.reduce(
    (sum, { discountAmount, buyNum }) => sum + discountAmount * buyNum,
    0
  );

  invoiceTypeChange();
};

const getDetailInfo = async () => {
  const { data } = await getOrderDetail(orderId);
  factoryInfo.value = data.orderDetailGroup.find(item => {
    if (item.factorId === factorId) {
      item.list = item.list.map(item => ({
        ...item,
        discountRate: 100,
        discountAmount: 0,
        actualAmount: calcTotal(item, 100)
      }));
      return item;
    }
  });

  detailInfo.value = data;
  detailInfo.value.receivingType = 1;
  // dealState { value: "21", label: "待测量" },{ value: "22", label: "已测量" }
  // factoryInfo.value.list = factoryInfo.value.list.filter(
  //   item => item.dealState !== 21 && item.dealState !== 22 && item.isSheft === 1 && item.buyNum != 0 && item.buyPartNum != 0
  // );
  factoryInfo.value.list = factoryInfo.value.list.filter(
    item => item.canMeasure == 1 && item.isSheft === 1 && item.buyNum != 0 && item.buyPartNum != 0
  );
  detailInfo.value.isBusinessInvoice = JSON.parse(JSON.stringify(factoryInfo.value.isSupportBilling));

  // 测试地址信息取客户地址信息
  if (!detailInfo.value.receivingName) {
    detailInfo.value.receivingName = detailInfo.value.customerName;
    detailInfo.value.receivingMobile = detailInfo.value.customerMobileCode;
    detailInfo.value.receivingAddress = detailInfo.value.customerAddress;
  }

  calcTotalPrice();
};

const getWarehouseList = async () => {
  const { data } = await getlistByTenantId();
  warehouseList.value = data.map(({ warehouseName, warehouseId }) => ({ label: warehouseName, value: warehouseId }));
};

const getPayAccountListFn = async () => {
  const { data } = await getPayAccountList({ factoryId: factorId });
  payAccountList.value = data;
};

const handleSelectionChange = selected => {
  selectedList.value = selected;
  calcTotalPrice();
};

const openUpdateReceiptInfoModal = () => {
  let ids = [];
  if (detailInfo.value.receivingAreaIds) {
    ids = detailInfo.value?.receivingAreaIds.split(",");
  }
  detailInfoCache.value = {
    ...detailInfo.value,
    receivingAreaIds: ids
  };
  updateReceiptInfoFlag.value = true;
};

const successHandle = (msg, val) => {
  // 如果组件传过来的省市区汉字没有值，取receivingAddress里的省市区值
  // 弹窗回显省市区，不进行修改，传回来是null
  if (!val.receivingAreaDetail) {
    val.receivingAreaDetail = detailInfo.value.receivingAreaDetail;
  }
  detailInfo.value = { ...detailInfo.value, ...val };
};

const handelClickCreateProcure = async item => {
  await formRef.value.validate();

  let params = {
    orderId,
    productInfos: selectedList.value,
    receivingName: item.receivingName,
    receivingMobile: item.receivingMobile,
    receivingAreaIds: item.receivingAreaIds,
    receivingAreaDetail: item.receivingAreaDetail,
    receivingAddress: item.receivingAddress,
    expectedMeasureTime: item.expectedMeasureTime,
    isBusinessInvoice: item.isBusinessInvoice,
    invoiceType: item.invoiceType,
    remark: item.remark
  };

  if (selectedList.value.length == 0) {
    ElMessage.error("请选择商品");
    return;
  }

  if (detailInfo.value.isBusinessInvoice == 1 && !detailInfo.value.invoiceType) {
    ElMessage.error("请选择开票类型");
    return;
  }

  params.productInfos = selectedList.value;

  await createMeasureOrder(params);

  purchaseSuccessFlag.value = true;
};

const rules = ref({
  expectedMeasureTime: [{ required: true, message: "请输入测量时间", trigger: "blur" }],
  isBusinessInvoice: [{ required: true, message: "请选择是否开票", trigger: "blur" }]
});

// 是否开票变化
const isBusinessInvoiceChange = () => {
  detailInfo.value.invoiceType = null;
  invoiceTypeChange();
};

// 开票类型变化-算开票金额和税额
const invoiceTypeChange = () => {
  let num = 0;
  // 支持开票-取开票的税率，不支持取0
  if (factoryInfo.value.isSupportBilling == 1) {
    if (detailInfo.value.invoiceType == 1) {
      num = Number(factoryInfo.value.specialTicket || 0);
    } else if (detailInfo.value.invoiceType == 2) {
      num = Number(factoryInfo.value.ordinaryTicket || 0);
    }
  }
  // 小数点2位 *1000 避免长度失真
  detailInfo.value.feeAmount = (((calcActualTotal(selectedList.value) * 1000) / 100) * num * 1000) / 1000000;
};

onMounted(() => {
  getDetailInfo();
  getWarehouseList();
  getPayAccountListFn();
});
</script>
<style lang="scss">
.order_purchase {
  height: 100%;
  overflow: hidden;
  .purchase_head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 60px;
    border-bottom: 1px solid #e2e8f0;
    .head_left {
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 18px;
      color: #131414;
      line-height: 24px;
      .round {
        width: 6px;
        height: 6px;
        background-color: #409eff;
        border-radius: 50%;
      }
    }
    .right_btn {
      background: #f2f3f5;
      border: none;
      width: 90px;
    }
  }
  .purchase_content {
    box-sizing: border-box;
    height: calc(100% - 60px);
    overflow: auto;
    .info_box {
      display: flex;
      justify-content: space-between;
      gap: 20px;
      padding: 20px;
      background: #f6f8fa;
      line-height: 24px;
      div {
        white-space: nowrap;
      }
      .info_label {
        color: #86909c;
      }
      .info_title {
        color: #86909c;
        font-size: 16px;
      }
    }
    .content_table {
      padding: 20px;
      .content_title {
        display: flex;
        justify-content: space-between;
        font-size: 18px;
        color: #3d3d3d;
        line-height: 22px;
      }
      .table_head {
        background: #f2f6fc !important;
      }
      .goods_cell {
        display: grid;
        grid-template-columns: 80px calc(100% - 100px);
        gap: 20px;
        .cell_image {
          width: 80px;
          height: 80px;
          border-radius: 4px;
        }
        .cell_product {
          .product_name {
            color: #3d3d3d;
            font-weight: 700;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 24px;
          }
          .product_info {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 12px;
            color: #86909c;
            line-height: 20px;
          }
        }
      }
    }
    .content_form {
      display: flex;
      border-top: 1px solid #e2e8f0;
      .form_content {
        box-sizing: border-box;
        width: calc(65% - 1px);
        padding: 20px;
        border-right: 1px solid #e2e8f0;
      }
      .form_info {
        box-sizing: border-box;
        width: 35%;
        background: #f6f8fa;
      }
      .img_upload {
        box-sizing: border-box;
        padding: 10px;
        width: 80px;
        height: 80px;
        background: #f2f3f5;
        text-align: center;
        color: #c9cdd4;
      }
    }
  }
  .warehouse_content {
    width: 100%;
    height: 58px;
    border: 1px solid #dcdfe6;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    padding-left: 20px;
    overflow: hidden;
    .el-select {
      width: 50%;
    }
  }
  .affix_content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20px;
    padding: 10px 20px;
    background: white;
    color: #3d3d3d;
    box-shadow: 0px -3px 10px 0px #04183019;
    .content_left {
      display: flex;
      align-items: end;
      .left_tip {
        font-size: 12px;
      }
      .info_lable {
        color: #86909c;
      }
      .info_price {
        color: #ff3333;
      }
    }
  }
  .procure_success {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    div:nth-child(2) {
      margin: 50px;
    }
  }
  .time_content {
    text-align: center;
    p {
      font-size: 14px;
      margin-top: 10px;
    }
  }
  .clear_btn {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px 0 0 0;
  }
  .row_input {
    width: 80px !important;
    .el-input__wrapper {
      background: white;
    }
  }

  .business-invoice {
    display: flex;
    flex-direction: row;
    align-items: center;
    .is-business-invoice {
      display: flex;
      flex-direction: row;
      align-items: center;
      margin-right: 40px;
      .el-radio {
        margin-right: 10px;
      }
      .radio-button {
        .el-radio-button {
          margin-right: 8px;
          .el-radio-button__inner {
            border-left: 1px solid #dcdfe6;
          }
          &.is-active {
            .el-radio-button__inner {
              border-left: 1px solid #007dff;
            }
          }
        }
      }
    }
  }

  .content_right {
    .btn {
      padding: 8px 32px;
    }
    .right_btn {
      background: #f2f3f5;
      border: none;
      width: 90px;
    }
  }
}
</style>
